package org.yaukie.auth.handler;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.yaukie.auth.constant.AjaxResult;
import org.yaukie.auth.constant.AuthCons.Login;
import org.yaukie.auth.entity.LoginUser;
import org.yaukie.auth.service.api.TokenHandlerService;
import org.yaukie.base.redis.RedisOrMapCache;
import org.yaukie.base.util.ServletUtils;
import org.yaukie.base.util.StringTools;

@Component
public class LoginOutSuccessHandler implements LogoutSuccessHandler, Serializable {
    private static final Logger log = LoggerFactory.getLogger(LoginOutSuccessHandler.class);
    @Autowired
    private RedisOrMapCache redisOrMapCache;
    @Autowired
    private TokenHandlerService tokenHandlerService;

    public LoginOutSuccessHandler() {
    }

    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (log.isInfoEnabled()) {
            log.info("系统模块{}执行注销处理.....", this.getClass().getSimpleName());
        }

        LoginUser loginUser = this.tokenHandlerService.getLoginUser(request);
        int code = Login.LOGIN_OUT.getCode();
        String msg = Login.LOGIN_OUT.getDes();
        if (StringTools.isNotNull(loginUser)) {
            this.tokenHandlerService.delLoginUser(loginUser.getToken());
        }

        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
